package com.rise.gpsapp;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;

import com.rise.externalservice.IGPS;

public class GPSServiceListener implements ServiceListener {

	private BundleContext context;
	private ConsumerThread consumerThread;
	private ServiceReference ref;
	
	public GPSServiceListener(BundleContext context, ConsumerThread ct) {
		this.context = context;
		this.consumerThread = ct;
	}
	
	public void serviceChanged(ServiceEvent event) {
		this.ref = event.getServiceReference();
		IGPS service = (IGPS) this.context.getService(this.ref);
		
		switch (event.getType()) {
			case ServiceEvent.REGISTERED:
				this.startUsingService(service);
				break;
			case ServiceEvent.MODIFIED:
				this.stopUsingService();
				this.ref = event.getServiceReference();
				service = (IGPS) this.context.getService(this.ref);
				this.startUsingService(service);
				break;
			case ServiceEvent.UNREGISTERING:
				this.stopUsingService();
				break;
		}

	}
	
	private void startUsingService(IGPS service){
		this.consumerThread.setGPSService(service);
	}
	
	public void stopUsingService(){
		if (this.consumerThread != null) {
			this.consumerThread.stopThread();
			try { this.consumerThread.join(); } catch (InterruptedException e) { }
			this.consumerThread = null;
		}
		if (this.ref != null) {
			this.context.ungetService(this.ref);
		}
	}
	
	public void setConsumer(ConsumerThread ct){
		this.consumerThread = ct;
	}

}
